package com.kun.utils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

@Component
public class DataSourceUtils {


    /**
     * 备份数据库
     * @param host host地址，可以是本机也可以是远程
     * @param userName 数据库的用户名
     * @param password 数据库的密码
     * @param backupFolderPath 备份的路径
     * @param fileName 备份的文件名
     * @param database 需要备份的数据库的名称
     * @return
     * @throws IOException
     */
    public static boolean backupMysqlDataSource(String host,
                                                String mysqlDockerName,
                                                String userName,
                                                String password, String backupFolderPath, String fileName, String database) throws Exception {
        File backupFolderFile = new File(backupFolderPath);
        if (!backupFolderFile.exists()) {
            // 如果目录不存在则创建
            backupFolderFile.mkdirs();
        }
        if (!backupFolderPath.endsWith(File.separator) && !backupFolderPath.endsWith("/")) {
            backupFolderPath = backupFolderPath + File.separator;
        }
        // 拼接命令行的命令
        String backupFilePath = backupFolderPath + fileName;
        StringBuilder stringBuilder = new StringBuilder();
        if (System.getProperty("os.name").toLowerCase().startsWith("win")){         //如果是win系统
            stringBuilder.append("mysqldump --opt")
                    .append(" --add-drop-database")
                    .append(" --add-drop-table");
            stringBuilder.append(" -h").append(host).append(" -u").append(userName).append(" -p").append(password);
            stringBuilder.append(" --result-file=").append(backupFilePath).append(".sql").append(" --default-character-set=utf8 ").append(database);
        }else{          //linux系统
            stringBuilder.append("docker exec -i ")
                    .append(mysqlDockerName)
                    .append(" mysqldump  -h").append(host)
                    .append(" -u").append(userName).append(" -p").append(password)
                    .append(" -C --default-character-set=utf8 ").append(database)
                    .append(" > ").append(backupFilePath).append(".sql");
        }
        //命令行
//        System.out.println(stringBuilder.toString());
        // 调用外部执行 exe 文件的 Java API
        Process process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));
        if (process.waitFor() == 0) {
            // 0 表示线程正常终止
            System.out.println("数据已经备份到 " + backupFilePath + " 文件夹中");
            return true;
        }
        System.out.println(process.getInputStream());
        System.out.println(process.getErrorStream());

        System.out.println(process.exitValue());
        byte[] bytes = new byte[process.getInputStream().available()];
        process.getInputStream().read(bytes);
        System.out.println(new String(bytes));
        process.getErrorStream().read(bytes);
        System.out.println(new String(bytes));
        return false;
    }

    private static String[] getCommand(String command) {
        String os = System.getProperty("os.name");
        String shell = "/bin/bash";
        String c = "-c";
        if(os.toLowerCase().startsWith("win")){
            shell = "cmd";
            c = "/c";
        }
        String[] cmd = { shell, c, command };
        return cmd;
    }


}
